package shared.gui;

import shared.client.Client;
import shared.mess.Message;
import shared.server.Server;
import shared.util.Util;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.InetAddress;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.*;


/**
 * @author akaovi
 * @createTime 2022/9/18 10:32
 */
public class SharedGUI extends JFrame {

    private Server server = null;
    private Client client = null;
    private ThreadPoolExecutor threadPool = null;

    private InetAddress targetIp = null;

    //构造器
    public SharedGUI() {
        this.threadPool = new ThreadPoolExecutor(7, 17, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>());

        // 通用字体
        Font font = new Font(null, Font.BOLD, 16);

        this.setLayout(null);
        JLabel jb = new JLabel();
        setTitle("SharedBox");//窗口标题
        this.setBounds(200, 100, 800, 600); // 设置大小
        this.setLocationRelativeTo(null);  // 屏幕正中间

        setResizable(false);// 设置窗体是否可以调整大小，参数为布尔值
        this.add(jb);//将其加入到窗口当中

        Toolkit kit = Toolkit.getDefaultToolkit();
        Image image = kit.getImage("src//image//0x1f4dd.png"); //设置窗口图标路径
        setIconImage(image); //换掉窗体样式

        // 添加组件
        // 文本同步
        JLabel userLabel1 = new JLabel("文本同步:");
        userLabel1.setBounds(10, 20, 100, 25);
        userLabel1.setFont(font);
        this.add(userLabel1);

        // 文本输入框
        JTextArea SendString = new JTextArea();
        SendString.setBounds(110, 20, 300, 100);
        SendString.setLineWrap(true);
        this.add(SendString);

        // 提交按钮
        JButton jButton1 = new JButton("提交");
        jButton1.setFont(font);
        jButton1.setFocusPainted(false);
        jButton1.setBounds(420, 20, 70, 25);
        this.add(jButton1);

        // 文本同步展示
        JLabel userLabel2 = new JLabel("文本同步:");
        userLabel2.setBounds(10, 130, 100, 25);
        userLabel2.setFont(font);
        this.add(userLabel2);

        // 同步展示框
        JTextArea showTextArea = new JTextArea();
        showTextArea.setBounds(110, 130, 300, 350);
        showTextArea.setLineWrap(true);
        showTextArea.setEditable(false);
        this.add(showTextArea);

        // 拉取更新
        JButton jButton2 = new JButton("更新");
        jButton2.setFont(font);
        jButton2.setFocusPainted(false);
        jButton2.setBounds(420, 130, 70, 25);
        this.add(jButton2);

        // 文本序号
        JLabel jLabel1 = new JLabel("待复制文本序号: ");
        jLabel1.setBounds(10, 490, 150, 25);
        jLabel1.setFont(font);
        this.add(jLabel1);

        // 填写序号
        JTextField copyNum = new JTextField();
        copyNum.setBounds(160, 490, 50, 25);
        this.add(copyNum);

        // 点击复制
        JButton jButton3 = new JButton("点击复制");
        jButton3.setFont(font);
        jButton3.setFocusPainted(false);
        jButton3.setBounds(230, 490, 100, 25);
        this.add(jButton3);

        // 连接到
        JLabel jLabel2 = new JLabel("连接到IP(IPv4): ");
        jLabel2.setFont(font);
        jLabel2.setBounds(190, 520, 120, 25);
        this.add(jLabel2);

        // IP填写框
        JTextField ipTextField = new JTextField();
        ipTextField.setBounds(320, 520, 100, 25);
        this.add(ipTextField);

        // 状态
        JLabel jLabel5 = new JLabel();
        jLabel5.setBounds(500, 230, 170, 25);
        jLabel5.setFont(font);
        jLabel5.setVisible(false);
        this.add(jLabel5);

        // 修改按钮
        JButton jButton4 = new JButton("修改");
        jButton4.setFont(font);
        jButton4.setFocusPainted(false);
        jButton4.setBounds(430, 520, 70, 25);
        jButton4.setEnabled(false);
        this.add(jButton4);

        // 确认
        JButton jButton5 = new JButton("确认");
        jButton5.setFont(font);
        jButton5.setFocusPainted(false);
        jButton5.setBounds(520, 520, 70, 25);
        jButton5.addActionListener(e -> {
            // 校验
            if ("".equals(ipTextField.getText())) {
                JOptionPane.showMessageDialog(
                        null,
                        "IP不能为空",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                InetAddress ip = Util.getIpAddress(ipTextField.getText());
                if (ip == null) {
                    JOptionPane.showMessageDialog(
                            null,
                            "ip填写有误",
                            "警告",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    jLabel5.setText("连接到: " + ipTextField.getText());
                    jLabel5.setVisible(true);
                    jButton4.setEnabled(true);
                    ipTextField.setEditable(false);
                    jButton5.setEnabled(false);
                    this.targetIp = ip;
                    JOptionPane.showMessageDialog(
                            null,
                            "连接到: " + ipTextField.getText(),
                            "提示",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });
        this.add(jButton5);

        // 给button4添加响应事件
        jButton4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("修改");
                jButton5.setEnabled(true);
                ipTextField.setEditable(true);
                jButton4.setEnabled(false);
            }
        });

        // 文件路径
        JLabel jLabel3 = new JLabel("文件路径 ");
        jLabel3.setBounds(500, 20, 100, 25);
        jLabel3.setFont(font);
        this.add(jLabel3);

        // 路径框
        JTextArea filePathTextArea = new JTextArea();
        filePathTextArea.setBounds(500, 50, 250, 100);
        filePathTextArea.setFont(new Font(null, Font.PLAIN, 18));
        filePathTextArea.setLineWrap(true);
        filePathTextArea.setEditable(false);
        this.add(filePathTextArea);

        // 选择文件
        JButton jButton6 = new JButton("选择文件");
        jButton6.setBounds(500, 160, 100, 25);
        jButton6.setFocusPainted(false);
        jButton6.setFont(font);
        jButton6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //按钮点击事件
                JFileChooser chooser = new JFileChooser();             //设置选择器
                int returnVal = chooser.showOpenDialog(jButton6);        //是否打开文件选择框
                if (returnVal == JFileChooser.APPROVE_OPTION) {          //如果符合文件类型
                    String filepath = chooser.getSelectedFile().getAbsolutePath();      //获取绝对路径
                    filePathTextArea.setText(filepath);
                }
            }
        });
        this.add(jButton6);

        // 发送
        JButton sendFile = new JButton("发送文件");
        sendFile.setBounds(650, 160, 100, 25);
        sendFile.setFont(font);
        sendFile.setFocusPainted(false);
        sendFile.addActionListener(e -> {
            if ("".equals(filePathTextArea.getText())) {
                JOptionPane.showMessageDialog(
                        null,
                        "无文件被选中",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            } else if (ipTextField.isEditable()) {
                JOptionPane.showMessageDialog(
                        null,
                        "IP正处于修改状态，不可发送",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int res = JOptionPane.showConfirmDialog(
                        null,
                        "确认发送",
                        "提示",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (res == 0) {
                    threadPool.execute(() -> {
                        if (client == null || client.getTargetIp() != this.targetIp) {
                            this.client = new Client(this.targetIp, 17777);
                        }
                        Message ms = Util.getFileMessage(filePathTextArea.getText().replace("\\", "/"));
                        client.send(ms);
                    });
                }
            }

        });
        this.add(sendFile);

        // 是否开启接收功能
        JLabel jLabel4 = new JLabel("接收功能:");
        jLabel4.setBounds(500, 200, 80, 25);
        jLabel4.setFont(font);
        this.add(jLabel4);

        // 是
        JButton jButton8 = new JButton("开");
        jButton8.setFocusPainted(false);
        jButton8.setFont(font);
        jButton8.setBounds(590, 200, 60, 25);
        this.add(jButton8);

        // 否
        JButton jButton9 = new JButton("关");
        jButton9.setEnabled(false);
        jButton9.setFocusPainted(false);
        jButton9.setFont(font);
        jButton9.setBounds(660, 200, 60, 25);
        jButton9.addActionListener(e -> {
            if (server != null) {
                server.setLoop(false);
                JOptionPane.showMessageDialog(
                        null,
                        "接收功能关闭啦",
                        "提示",
                        JOptionPane.INFORMATION_MESSAGE);
                jButton9.setEnabled(false);
                jButton8.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(
                        null,
                        "你他妈的没开启接收功能",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            }
        });
        this.add(jButton9);

        // 给 是 按钮添加响应事件
        jButton8.addActionListener(e -> {
            // 开启
            threadPool.execute(() -> {
                if (server == null) {
                    this.server = new Server(threadPool, 17777);
                }
                this.server.accept();
            });
            jButton8.setEnabled(false);
            jButton9.setEnabled(true);
            JOptionPane.showMessageDialog(
                    null,
                    "接收功能开启啦",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);

        });

        // 给 提交 添加响应事件
        jButton1.addActionListener(e -> {
            if ("".equals(SendString.getText())) {
                JOptionPane.showMessageDialog(
                        null,
                        "不能发送空字符串",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            } else if (ipTextField.isEditable()) {
                JOptionPane.showMessageDialog(
                        null,
                        "IP正处于修改状态，不可发送",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int res = JOptionPane.showConfirmDialog(
                        null,
                        "确认发送",
                        "提示",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (res == 0) {
                    // 发送
                    threadPool.execute(() -> {
                        if (client == null || client.getTargetIp() != this.targetIp) {
                            this.client = new Client(this.targetIp, 17777);
                        }
                        Message ms = Util.getTextMessage(SendString.getText());
                        this.client.send(ms);
                    });
                    System.out.println("提交: " + SendString.getText());
                }
            }
        });

        // 拉取更新
        jButton2.addActionListener(e -> {
            if (ipTextField.isEditable()) {
                JOptionPane.showMessageDialog(
                        null,
                        "IP正处于修改状态，无法更新",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int res = JOptionPane.showConfirmDialog(
                        null,
                        "是否更新",
                        "提示",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (res == 0) {
                    try {
                        showTextArea.setText(server.getCache().toString());
                    } catch (Exception exception) {
                        JOptionPane.showMessageDialog(
                                null,
                                "对方未开启服务",
                                "提示",
                                JOptionPane.INFORMATION_MESSAGE);
                    }

                }
            }
        });

        // 点击复制
        jButton3.addActionListener(e -> {
            if ("".equals(showTextArea.getText())) {
                JOptionPane.showMessageDialog(
                        null,
                        "展示框无内容",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            } else if ("".equals(copyNum.getText())) {
                JOptionPane.showMessageDialog(
                        null,
                        "请填写待复制内容的序号",
                        "警告",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                if (Util.isIllegal(copyNum.getText())) {
                    String text = server.getCache().getDetails(copyNum.getText());
                    // 获取系统剪贴板
                    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                    // 封装文本内容
                    Transferable trans = new StringSelection(text);
                    // 把文本内容设置到系统剪贴板
                    clipboard.setContents(trans, null);
                    JOptionPane.showMessageDialog(
                            null,
                            "复制成功",
                            "提示",
                            JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(
                            null,
                            "不合法的输入",
                            "警告",
                            JOptionPane.WARNING_MESSAGE);
                }

            }
        });

        // 是否开启拒收功能
        JLabel refuseAllFiles = new JLabel("拒接文件:");
        refuseAllFiles.setBounds(500, 260, 80, 25);
        refuseAllFiles.setFont(font);
        this.add(refuseAllFiles);

        // 设置拒接所有文件的模式
        JButton jButton10 = new JButton("开");
        jButton10.setFocusPainted(false);
        jButton10.setFont(font);
        jButton10.setBounds(590, 260, 60, 25);
        this.add(jButton10);

        JButton jButton11 = new JButton("关");
        jButton11.setEnabled(false);
        jButton11.setFocusPainted(false);
        jButton11.setFont(font);
        jButton11.setBounds(660, 260, 60, 25);
        jButton11.addActionListener(e -> {
            this.server.setRefuseAllFiles(false);
            jButton10.setEnabled(true);
            jButton11.setEnabled(false);
            JOptionPane.showMessageDialog(
                    null,
                    "拒接文件模式已关闭",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
        });
        this.add(jButton11);

        jButton10.addActionListener(e -> {
            if (jButton9.isEnabled()) {
                int res = JOptionPane.showConfirmDialog(
                        null,
                        "确认是否开启举手文件模式，拒收文件，并不再提醒",
                        "拒收文件",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (res == 0) {
                    this.server.setRefuseAllFiles(true);
                    jButton10.setEnabled(false);
                    jButton11.setEnabled(true);
                    JOptionPane.showMessageDialog(
                            null,
                            "拒接文件模式已开启",
                            "提示",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(
                        null,
                        "请先开启接收服务",
                        "提示",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        });

        // 收尾
        setDefaultCloseOperation(EXIT_ON_CLOSE);// 用户点击窗口关闭
        this.setVisible(true);//设置是否窗口显示

        addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {

            }

            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    if (threadPool != null) {
                        threadPool.shutdown();
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }

            @Override
            public void windowClosed(WindowEvent e) {

            }

            @Override
            public void windowIconified(WindowEvent e) {

            }

            @Override
            public void windowDeiconified(WindowEvent e) {

            }

            @Override
            public void windowActivated(WindowEvent e) {

            }

            @Override
            public void windowDeactivated(WindowEvent e) {

            }
        });
    }

    //定义主方法
    public static void main(String[] args) {
        new SharedGUI();//调用方法
    }
}
